package com.fushenlan.epidemicControl.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.fushenlan.Vo.EmergencyInfoVo;
import com.fushenlan.commons.GeneralResponse;
import com.fushenlan.epidemicControl.dto.EmergencyInfoDto;
import com.fushenlan.epidemicControl.mapper.BuildingInfoMapper;
import com.fushenlan.epidemicControl.mapper.EmergencyInfoMapper;
import com.fushenlan.epidemicControl.mapper.InhabitantInfoMapper;
import com.fushenlan.epidemicControl.mapper.NeighborhoodMemberMapper;
import com.fushenlan.epidemicControl.service.EmergencyInfoService;
import com.fushenlan.excel.ExportExcelUtil;
import com.fushenlan.helper.ListPageHelper;
import com.fushenlan.po.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @Author XUJIN
 * @DATE 2022/4/24
 * @PACKAGE_NAME com.fushenlan.epidemicControl.service.Impl
 * @VERSION 1.0
 */
@Service
@Slf4j
public class EmergencyInfoServiceImpl implements EmergencyInfoService {

    private static final String EXPORT_EMERGENCY_FILENAME = "所属居委求助信息列表一览";

    private static final String EXPORT_EMERGENCY_TITLE = "紧急求助列表";

    @Autowired
    private EmergencyInfoMapper emergencyInfoMapper;

    @Autowired
    private InhabitantInfoMapper inhabitantInfoMapper;

    @Autowired
    private BuildingInfoMapper buildingInfoMapper;

    @Autowired
    private NeighborhoodMemberMapper neighborhoodMemberMapper;

    /**
     * 查询求助信息，并封装数据至前端
     * @param emergencyInfoDto
     * @return
     */
    @Override
    public GeneralResponse findAllEmergencyList(EmergencyInfoDto emergencyInfoDto, int pageNo, int pageSize) {

        //分页
        PageHelper.startPage(pageNo,pageSize);
        List<EmergencyInfoVo> allEmergencyList = emergencyInfoMapper.findAllEmergencyList(emergencyInfoDto);
        allEmergencyList.forEach(tmp->{
            if (StringUtil.isNotEmpty(tmp.getDealId())){  //如果处理人不为空
                //根据用户ID去居民表查询
                InhabitantInfo info = inhabitantInfoMapper.selectById(tmp.getDealId());
                if (info != null){
                    tmp.setDealName(info.getUserName());
                }

            }
        });
        PageInfo<EmergencyInfoVo> pageInfo = new PageInfo<EmergencyInfoVo>(allEmergencyList);
        PageInfoVo pageDateInfoVo = ListPageHelper.StartPage(pageInfo);

        //未处理数量
        long noDealCount = allEmergencyList.stream().filter(tmp -> "1".equals(tmp.getState())).count();
        long DealIngCount = allEmergencyList.stream().filter(tmp -> "2".equals(tmp.getState())).count();
        long dealedCount = allEmergencyList.stream().filter(tmp -> "3".equals(tmp.getState())).count();

        pageDateInfoVo.setDealedNum(dealedCount);
        pageDateInfoVo.setDealingNum(DealIngCount);
        pageDateInfoVo.setNoDealNum(noDealCount);

        return  GeneralResponse.success(pageDateInfoVo);
    }

    /**
     * 查看单个求助信息
     * @param id
     * @return
     */
    @Override
    public EmergencyInfoVo getEmergencyInfoById(Integer id) {
        EmergencyInfoVo emergencyInfoById = emergencyInfoMapper.getEmergencyInfoById(id);
        if (emergencyInfoById != null){
            //获取求助用户信息
            String userId = emergencyInfoById.getUserId();
            InhabitantInfo info = inhabitantInfoMapper.selectById(userId);
            StringBuilder sb = new StringBuilder();
            //依次封装地址消息  小区、楼栋、房间号
            //拼接家庭住址信息
                BuildingInfo bi = new BuildingInfo();
                bi.setId(info.getResidentialId())
                        .setLevel(1);
                List<BuildingInfo> clist = buildingInfoMapper.findList(bi);
                if (CollectionUtil.isNotEmpty(clist)){
                    sb.append(clist.get(0).getName());
                }
                bi.setId(info.getBuildingId())
                        .setLevel(2);
                List<BuildingInfo> blist = buildingInfoMapper.findList(bi);
                if (CollectionUtil.isNotEmpty(blist)){
                    sb.append(blist.get(0).getName());
                }
                bi.setId(info.getHouseId())
                        .setLevel(3);
                List<BuildingInfo> rlist = buildingInfoMapper.findList(bi);
                if (CollectionUtil.isNotEmpty(rlist)){
                    sb.append(rlist.get(0).getName());
                }
            InhabitantInfo dealInfo = inhabitantInfoMapper.selectById(emergencyInfoById.getDealId());
            if (dealInfo != null){
                emergencyInfoById.setDealName(dealInfo.getUserName());
            }
            emergencyInfoById.setAddress(sb.toString());
        }
        return emergencyInfoById;
    }


    /**
     * 处理求助信息/分配紧急度，填写处理结果
     * @param
     * @param
     * @return
     */
    @Override
    @Transactional
    public GeneralResponse dealEmergency(@RequestBody  EmergencyInfoDto emergencyInfoDto) {

        EmergencyInfoVo emergencyInfoById = emergencyInfoMapper.getEmergencyInfoById(emergencyInfoDto.getId());
        int row = 0;
        try {
            EmergencyInfo emergencyInfo = new EmergencyInfo();
            emergencyInfo.setId(emergencyInfoById.getId());
            if (StringUtil.isNotEmpty(emergencyInfoDto.getResult())){
                emergencyInfo.setResult(emergencyInfoDto.getResult());
                emergencyInfo.setDealTime(new Date());
                emergencyInfo.setState("3");
            }

            //设置处理人，dealid来自居委成员表，可通过接口调用获取
//            if (emergencyInfoDto.getInhabitantId() != null && "1".equals(emergencyInfoById.getState())){  //如果处理人不为空
//                emergencyInfo.setDealId(emergencyInfoDto.getInhabitantId()+"");
//                emergencyInfo.setState("2");//处理中
//            }
            //分配处理人
            if (StringUtils.isNotEmpty(emergencyInfoDto.getDealId())){
                emergencyInfo.setDealId(emergencyInfoDto.getDealId());
            }

            if (StringUtil.isNotEmpty(emergencyInfoDto.getLevel())){
                emergencyInfo.setLevel(emergencyInfoDto.getLevel());
            }
            row = emergencyInfoMapper.dealEmergency(emergencyInfo);
            return row > 0 ? GeneralResponse.success() : GeneralResponse.fail();
        } catch (Exception e) {
            log.error("服务异常===>{}",e);
            return GeneralResponse.fail();
        }

    }


    /**
     * 导出求助信息excel列表
     * @param neighborId
     * @param response
     */
    @Override
    public void exportEmergencyInfo(Integer neighborId, HttpServletResponse response) {

        EmergencyInfoDto emergencyInfoDto = new EmergencyInfoDto();
        emergencyInfoDto.setNeighborId(neighborId);

        List<EmergencyInfoVo> allEmergencyList = emergencyInfoMapper.findAllEmergencyList(emergencyInfoDto);

        allEmergencyList.forEach(tmp->{
            if (StringUtil.isNotEmpty(tmp.getDealId())){  //如果处理人不为空
                //根据用户ID去居民表查询
                InhabitantInfo info = inhabitantInfoMapper.selectById(tmp.getDealId());
                if (info != null){
                    tmp.setDealName(info.getUserName());
                }

            }
        });

        ExportExcelUtil.exportExcel(allEmergencyList, EmergencyInfoVo.class,EXPORT_EMERGENCY_FILENAME,EXPORT_EMERGENCY_TITLE,response);

    }


    /**
     * 获取所有的居委工作人员
     * @param neighborId
     * @return
     */
    @Override
    public List<NeighborhoodMember> getNeighborMember(Integer neighborId) {
        NeighborhoodMember neighborhoodMember = new NeighborhoodMember();
        neighborhoodMember.setNeighborhoodId(neighborId);
        return neighborhoodMemberMapper.findNeighborMemberList(neighborhoodMember);
    }


    /**
     * 批量分配处理人
     * @param dealId 处理人
     * @param ids
     * @param level   紧急度
     * @return
     */
    @Override
    @Transactional
    public GeneralResponse batchAssignDealUser(String dealId, String level, String ids) {

        String[] split = ids.split(",");
        for (String id : split){
            Integer emergencyId= Integer.valueOf(id);
            EmergencyInfo emergencyInfo = emergencyInfoMapper.selectById(emergencyId);
            emergencyInfo.setDealId(dealId);
            emergencyInfo.setLevel(level);
            emergencyInfoMapper.updateById(emergencyInfo);
        }
        return GeneralResponse.success();
    }
}
